package com.jzhao.jpre.base.queue;

public class TestQueue {
	class Task implements Runnable {
		StringBuffer string = null;

		public Task(StringBuffer string) {
			this.string = string;
		}

		public void run() {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException ie) {
				System.out.println(ie);
			}
			string.append("EndTask");
		}
	}

	class Client implements Runnable {
		StringBuffer string = new StringBuffer();
		SyncTaskQueue stq = null;
		int seq = 0;

		public Client(int seq, SyncTaskQueue stq) {
			string.append(seq);
			this.stq = stq;
			this.seq = seq;
		}

		public void run() {
			Runnable task = new Task(string);
			synchronized (task) {
				try {
					if (stq.putTask(task)) {
						System.out.println("Client [" + string + "] start");
						task.wait();
						System.out.println("Client [" + seq + ":" + string + "] end");
					} else
						System.out.println("Client [" + string + "] failed");
				} catch (InterruptedException ie) {
					System.out.println(ie);
					System.out.println("Client [" + string + "] failed");
				}
			}
		}
	}

	public static void main(String[] args) {
		TestQueue tq = new TestQueue();
		SyncTaskQueue stq = new SyncTaskQueue(100);

		for (int i = 0; i < 50; i++) {
			new Thread(tq.new Client(i, stq)).start();
		}
		try {
			Thread.sleep(60000);
		} catch (InterruptedException ie) {
			System.out.println(ie);
		}
		stq.stop();
		for (int i = 0; i < 1; i++) {
			new Thread(tq.new Client(i, stq)).start();
		}
	}
}
